<?php
namespace app\middleware;

use think\facade\Session;

class Authorization
{
    //排除执行位置
    protected $exclude = [
        'login/index',
        'logout/index',
        'forget/index',
        'register/index'
    ];

    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle( $request, \Closure $next )
    {
        //当前执行位置
        $controller = $request->controller();
        $action = $request->action();
        $execute_router = $controller . '/' . $action;
        $execute_class = 'app\\controller\\' . str_replace( '.', '\\', $controller );

        //是否存在控制器
        if( class_exists( $execute_class ) )
        {
            //是否在排除名单里
            if( ! in_array( strtolower( $execute_router ), $this->exclude ) )
            {
                if( ! Session::has( 'member_id' ) )
                {
                    return json( [ 'code' => '10002', 'message' => 'permission denied' ] );
                }

                //csrf token
                if( ! $request->checkToken( '_csrf_token' ) )
                {
                    return json( [ 'code' => '10003', 'message' => 'bad form token' ] );
                }
                
                //bearer token
                if( $auth_token = $request->header( 'authorization' ) )
                {
                    $this->auth_token = substr( $auth_token, 7 );
                }

                if( ! $this->auth_token )
                {
                    return json( [ 'code' => '10004', 'message' => 'bad authorization token' ] );
                }
            }
        }

        return $next( $request );
    }
}
